package cn.e3mall.content.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
















import cn.e3mall.common.jedis.JedisClient;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.content.service.ContentService;
import cn.e3mall.mapper.TbContentMapper;
import cn.e3mall.pojo.TbContent;
import cn.e3mall.pojo.TbContentExample;
import cn.e3mall.pojo.TbContentExample.Criteria;
/**
 * 内容管理service
 * @author shanqingyun
 *
 */
@Service
public class ContentServiceImpl implements ContentService {
	
	
	@Autowired
	private TbContentMapper contentMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("$(CONTENT_LIST)")
	private String CONTENT_LIST;
	@Override
	public E3Result addContent(TbContent tbContent) {
		//设置content的属性
		tbContent.setCreated(new Date());
		tbContent.setUpdated(new Date());
		//插入到数据库
		contentMapper.insert(tbContent);
		//缓存通途删除缓存中对应的额数据
		jedisClient.hdel(CONTENT_LIST, tbContent.getCategoryId().toString());
		return E3Result.ok();
	}


	@Override
	public List<TbContent> getTbContentListByCid(long cid) {
		//查询缓存
		try {
			//若缓存中有直接响应结果
			String json = jedisClient.hget(CONTENT_LIST, cid+"");
			if(StringUtils.isNotBlank(json)){
				List<TbContent> list = JsonUtils.jsonToList(json, TbContent.class);
				return list;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//如果没有则查询数据库
		TbContentExample example=new TbContentExample();
		Criteria criteria = example.createCriteria();
		criteria.andCategoryIdEqualTo(cid);
		List<TbContent> list = contentMapper.selectByExampleWithBLOBs(example);
		//执行查询把结果添加到缓存
		try {
			jedisClient.hset(CONTENT_LIST,cid+"", JsonUtils.objectToJson(list));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
